let app = getApp();
let MD5 = require("../../../utils/md5util.js");
let template = "<xml><appid><![CDATA[APPID]]></appid><body><![CDATA[BODY]]></body><mch_id><![CDATA[MCH_ID]]></mch_id><nonce_str><![CDATA[NONCE_STR]]></nonce_str><sign>SIGN</sign><out_trade_no><![CDATA[OUT_TRADE_NO]]></out_trade_no><total_fee><![CDATA[TOTAL_FEE]]></total_fee><spbill_create_ip><![CDATA[SPBILL_CREATE_IP]]></spbill_create_ip><notify_url><![CDATA[NOTIFY_URL]]></notify_url><trade_type><![CDATA[TRADE_TYPE]]></trade_type><openid><![CDATA[OPENID]]></openid></xml>";
// pages/order/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: 0,
    srvAmount: 0,
    isDisplay: true,
    orderId: "",
    userIp: "",
    prepay_Id: "",
    appointment:{
      Y:0,
      M:0,
      D:0,
      H:0,
      Min:0,
      isActive:false
    },
    checkedSrv: [],
    csServices: [],
    store: "",
    details: {
      prodAmount: 0,
      Guid: "",
      Id: 0,
      Name: "",
      HourCost: 0,
      Description: "",
      PrdImage: "",
      ProdIds: [],
      Products: [],
      isActive: false
    },
    Product: {
      Id: 0,
      Name: "",
      Models: []
    },
    Model: {
      Id: 0,
      Name: "",
      Price: 0,
      isActive: false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        })
      }
    });
    that.setData({
      checkedSrv: options.checkedSrv.split(','),
      store: getApp().globalData.storeId ? getApp().globalData.storeId : ""
    })
    that.getServiceList();
    that.calcAmount();
  },

  addService: function(){
    let that = this;
    let temp = JSON.stringify(that.data.checkedSrv);
    wx.navigateTo({
      url: './serviceList/srvList?srvs=' + temp
    })
  },

  deleteSrv: function(event){
    let that = this;
    let selSrv = event.currentTarget.dataset.selsrv;
    if(that.data.checkedSrv.length == 1){
      wx.showToast({
        title: '至少保留一项服务或产品',
        icon: 'none',
        duration: 2200
      })
    }else{
      for (let i = 0; i < that.data.csServices.length; i++) {
        if (that.data.csServices[i].Id == selSrv) {
          that.data.csServices[i].isActive = false;
          that.data.checkedSrv.splice(that.data.checkedSrv.indexOf(selSrv.toString()), 1)
          that.setData({
            csServices: that.data.csServices,
            checkedSrv: that.data.checkedSrv
          })
          break;
        }
      }
    }
  },
  withAppointment: function (){
    let that = this;
    if (!that.data.appointment.isActive) {
        wx.navigateTo({
          url: './appointment/appointment'
        })
      that.setData({
        "appointment.isActive": !that.data.appointment.isActive
      });
    }else{
      that.setData({
        "appointment.isActive": !that.data.appointment.isActive
      });
    }
  },

  getServiceList: function(){
    let that = this;
    wx.request({
      url: 'https://www.limecar.cn/WxApi/ServiceList',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        let srvs = res.data;
        let tempsrvs = [];
        for(let i = 0; i < srvs.length; i++){
          that.handleSrv(srvs[i]);
          tempsrvs.push(that.data.details);
          that.setData({
            details: {}
          })
        }
        that.setData({
          csServices: tempsrvs
        });
        that.calcAmount();
      }
    });
  },

  handleSrv: function(srv){
    let that = this;
    that.setData({
      "details.HourCost": srv.HourCost,
      "details.prodAmount": srv.HourCost,
      "details.Id": srv.Id,
      "details.Description": srv.Description,
      "details.Name": srv.Name,
      "details.Guid": srv.Guid
    });
    if (that.data.checkedSrv.toString().indexOf(srv.Id) >= 0){
      that.setData({
        "details.isActive": "true"
      })
    }
    let source = srv.Products;
    let prodids = [];
    let target = [];
    for (let i = 0; i < source.length; i++) {
      let hasProd = false;
      for (let l = 0; l < target.length; l++) {
        if (target[l].Name == source[i].ProductName) {
          let modelTemp = {
            Id: source[i].CPTId,
            Name: source[i].Name,
            Price: source[i].Price,
            isActive: false
          }
          target[l].Models.push(modelTemp);
          hasProd = true;
          break;
        }
      }
      if (!hasProd) {
        let prodTemp = {
          Id: target.length + 1,
          Name: source[i].ProductName,
          Models: []
        };
        let modelTemp = {
          Id: source[i].CPTId,
          Name: source[i].Name,
          Price: source[i].Price,
          isActive: false
        };
        prodids.push("#")
        prodTemp.Models.push(modelTemp);
        target.push(prodTemp);
      }
    }
    that.setData({
      "details.Products": target,
      "details.ProdIds": prodids
    })
  },

  radioChange: function (event) {
    let that = this;
    let srvs = JSON.parse(JSON.stringify(that.data.csServices));
    let values = event.detail.value.split(';');
    let srvIndex = parseInt(values[0]);
    
    let prodids = srvs[srvIndex].ProdIds;
    let amount = srvs[srvIndex].prodAmount;
    let prod = srvs[srvIndex].Products[values[1]];
    let model = prod.Models[values[2]];

    if (prodids[values[1]] == '#')
    {
      amount = amount + parseInt(model.Price);
    }else{
      for (let c = 0; c < prod.Models.length; c++) {
        if (prod.Models[c].Id == prodids[values[1]]) {
          amount = amount - parseInt(prod.Models[c].Price) + parseInt(model.Price);
          break;
        }
      }
      
    }
    prodids[values[1]] = model.Id;
    that.data.csServices[srvIndex].prodAmount = amount;
    that.data.csServices[srvIndex].ProdIds = prodids;
    that.data.csServices[srvIndex].Products[values[1]].Models[values[2]].isActive = true;
    that.setData({
      csServices: that.data.csServices
    })
    that.calcAmount();
  },

  calcAmount: function(){
    let that = this;
    let total = 0;
    for(let i = 0; i < that.data.csServices.length; i++){
      if(that.data.csServices[i].isActive){
        total = total + that.data.csServices[i].prodAmount
      }
    }
    that.setData({
      srvAmount: total
    })
  },

  selStore: function(){
    wx.navigateTo({
      url: './stores/stores',
    })
  },

  checkout: function(){
    let that = this;
    let access = true;
    if (that.data.store == null || that.data.store == ""){
      wx.showToast({
        title: '请选择门店',
        icon: "none",
        duration: 2200
      })
      access = false;
    } else if(that.data.srvAmount == 0) {
      wx.showToast({
        title: '暂不能只选择免费服务项哦~',
        icon: "none",
        duration: 2200
      })
      access = false;
    } else {
      for(let i = 0; i < that.data.csServices.length; i++){
        if (that.data.csServices[i].isActive){
          if (JSON.stringify(that.data.csServices[i].ProdIds).indexOf('#') >= 0){
            wx.showToast({
              title: '请选择服务细节',
              icon: "none",
              duration: 2200
            })
            access = false;
            break;
          }
        }
      }
    }
    if (access){
      getApp().globalData.appointment = that.data.appointment;
      getApp().globalData.checkedSrv = that.data.checkedSrv;
      let hardCodeSrv = "";
      for(let i = 0; i < that.data.csServices.length; i++){
        if (that.data.csServices[i].isActive){
          hardCodeSrv = hardCodeSrv + that.data.csServices[i].Id + ":" + that.data.csServices[i].ProdIds.toString() + ";"
        }
      }
      that.submitOrder(that.data.orderId, hardCodeSrv);
      that.setData({
        isDisplay: "none"
      })
    }
  },

  cancel: function(){
    let that = this;
    wx.request({
      url: 'https://www.limecar.cn/Order/UpdateOrderState',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        orderId: that.data.orderId,
        State: 2
      },
      success: function (res) {
        console.log(res.data);
      }
    })
    that.setData({
      isDisplay: true
    })
  },

  submitOrder: function(orderId, srv){
    let that = this;
    let atime = "";
    if (that.data.appointment.Y != 0){
      atime = that.data.appointment.Y + '-' + that.data.appointment.M + '-' + that.data.appointment.D + ' ' + that.data.appointment.H + ':' + that.data.appointment.Min;
    }
    wx.request({
      url: 'https://www.limecar.cn/Order/SubOrder',
      data: {
        OrderId: orderId,
        ShopId: app.globalData.storeName,
        ServiceId: srv,
        Status: "",
        UserName: app.globalData.userInfo.nickName,
        UserId: app.globalData.userInfo.Id,
        Appointment: atime
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res){
        console.log(res);
        that.setData({
          orderId: res.data.result,
          userIp: res.data.ip
        })
        that.prePayment(res.data.result);
      }
    })
  },

  prePayment: function(orderId){
    let that = this;
    let nonce = that.getNonce(32);
    let signLocal = that.getSign(nonce);
    let temp = template.replace("APPID", app.globalData.appId);
    temp = temp.replace("BODY", app.globalData.body);
    temp = temp.replace("MCH_ID", app.globalData.mch_Id);
    temp = temp.replace("NONCE_STR", nonce);
    temp = temp.replace("SIGN", signLocal);
    temp = temp.replace("SPBILL_CREATE_IP", that.data.userIp);
    temp = temp.replace("OUT_TRADE_NO", orderId);
    temp = temp.replace("TOTAL_FEE", that.data.srvAmount);
    temp = temp.replace("TRADE_TYPE", "JSAPI");
    temp = temp.replace("NOTIFY_URL", "https://www.limecar.cn/Pay/PayResult");
    temp = temp.replace("OPENID", app.globalData.userInfo.openId);
    wx.request({
      url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
      header:{
        'Content-Type': 'application/xml'
      },
      method: "post",
      data: temp,
      success: function(res){
        console.log(res.data);
        let tempId = res.data.split('prepay_id');
        that.setData({
          prepay_Id: tempId[1].replace('><![CDATA[', '').replace(']]></', '')
        })
      },
      fail: function(res){
        console.log(res);
      }
    })
  },

  payment: function(){
    let that = this;
    if(that.data.prepay_Id != ""){
      let dateNow = new Date().getTime();
      let nonce = that.getNonce(32);
      let signLocal = that.getPaySign(nonce, dateNow);
      wx.requestPayment({
        timeStamp: dateNow.toString(),
        nonceStr: nonce,
        package: 'prepay_id=' + that.data.prepay_Id,
        signType: 'MD5',
        paySign: signLocal,
        success: function(res){
          wx.request({
            url: 'https://www.limecar.cn/Order/UpdateOrderState',
            header: {
              'Content-Type': 'application/json'
            },
            data:{
              orderId: that.data.orderId,
              State: 1
            },
            success: function (res) {
              console.log(res.data);
              wx.switchTab({
                url: '../../order/orderIndex',
              })
            }
          })
        },
        fail: function(res){
          console.log(res)
        }
      })
    }
  },

  getSign: function (nonce){
    let that = this;
    let stringLime = "appid=" + app.globalData.appId + "&body=" + app.globalData.body + "&mch_id=" + app.globalData.mch_Id + "&nonce_str=" + nonce + "&notify_url=https://www.limecar.cn/Pay/PayResult" + "&openid=" + app.globalData.userInfo.openId +"&out_trade_no=" + that.data.orderId + "&spbill_create_ip=" + that.data.userIp + "&total_fee=" + that.data.srvAmount + "&trade_type=JSAPI";
    let signTempStr = stringLime + "&key=" + app.globalData.limeKey;
    let sign = MD5.md5(signTempStr).toUpperCase();
    return sign;
  },

  getPaySign: function (nonce, time){
    let that = this;
    let stringLime = "appId=" + app.globalData.appId + "&nonceStr=" + nonce + "&package=prepay_id=" + that.data.prepay_Id + "&signType=MD5" + "&timeStamp=" + time;
    let signTempStr = stringLime + "&key=" + app.globalData.limeKey;
    let sign = MD5.md5(signTempStr).toUpperCase();
    return sign;
  },

  getNonce: function(length){
    let res = "";
    let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for (let i = 0; i < length; i++) {
      let id = Math.ceil(Math.random() * 52);
      res += chars[id];
    }
    return res;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    "abmnost"
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    console.log(that.data.newSrv);
    if (that.data.newSrv != null){
      console.log(that.data.checkedSrv);
      for (let i = 0; i < that.data.csServices.length; i++) {
        if (that.data.csServices[i].Id == that.data.newSrv) {
          that.data.csServices[i].isActive = true;
          that.data.checkedSrv.push(that.data.newSrv)
          that.setData({
            csServices: that.data.csServices,
            checkedSrv: that.data.checkedSrv
          })
          break;
        }
      }
      console.log(that.data.checkedSrv);
      that.calcAmount();
    }
    
    that.setData({
      store: getApp().globalData.storeName
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})